//
//  ChannelManageViewController.m
//  History
//
//  Created by jam on 16/9/5.
//  Copyright © 2016年 kane. All rights reserved.
//

#import "ChannelManageViewController.h"
#import "FilesViewController.h"


@interface ChannelManageViewController ()
{
    
    __weak IBOutlet UIScrollView *channelScroll;
    __weak IBOutlet UIButton *deleteBtn;
    __weak IBOutlet UIButton *createBtn;
    __weak IBOutlet UILabel *titleLabel;
    __weak IBOutlet UILabel *myChannelLabel;
    __weak IBOutlet UILabel *tipLabel;
    NSMutableArray *delBtntagAry;
    NSMutableArray *subjBtnAry;
    NSMutableArray *exchangeAry;
    NSInteger totalNumber;
    
    // 开始拖动的view的下一个view的CGPoint（如果开始位置是0 结束位置是4 nextPoint值逐个往下算）
    CGPoint nextPoint;
    
    // 用于赋值CGPoint
    CGPoint valuePoint;
}

@end

@implementation ChannelManageViewController
@synthesize channelAry , selectedIndex , delegate;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    delBtntagAry = [NSMutableArray array];
    subjBtnAry = [NSMutableArray array];
    exchangeAry = [NSMutableArray arrayWithArray:channelAry];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeBackgroundColor) name:kChangeNightMode object:nil];
//    [self initUI];
    [self changeBackgroundColor];
}
-(void)changeBackgroundColor
{
    titleLabel.textColor = KKColor_White_Black;
    myChannelLabel.textColor = KKColor_White_Black;
    for (int i = 0; i < channelAry.count; i++) {
        UIButton *btn = (UIButton *)[self.view viewWithTag:CellOffset+i+999];
        [btn setTitleColor:i == selectedIndex ?[UIColor orangeColor]: KKColor_White_Black forState:UIControlStateNormal];
    }
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self initUI];
}

-(void)initUI
{
    tipLabel.hidden = YES;
    
    deleteBtn.layer.cornerRadius = 5;
    deleteBtn.layer.borderColor = [UIColor orangeColor].CGColor;
    deleteBtn.layer.borderWidth = .5f;
    createBtn.layer.cornerRadius = 5;
    createBtn.layer.borderColor = [UIColor orangeColor].CGColor;
     createBtn.layer.borderWidth = .5f;
    
    for (NSInteger i = 0; i < channelAry.count; i++) {
        UIView *bgView = [[UIView alloc] init];
        bgView.tag = CellOffset+i;
        bgView.backgroundColor = [UIColor whiteColor];
        bgView.frame = CGRectMake((i%3)*105+10, (i/3)*50+45, 95, 35);
        bgView.layer.cornerRadius = 5;
        [bgView drawBorderColor:[UIColor lightGrayColor] Width:.5];
        if (i != 0) {
            UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(showCloseBtn:)];
            [bgView addGestureRecognizer:longPress];
            // 添加拖拽手势
            UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
            [pan setMaximumNumberOfTouches:1]; // 最小手指数
            [pan setMaximumNumberOfTouches:2]; // 最大手指数
            //        [bgView addGestureRecognizer:pan];
        }
        [channelScroll addSubview:bgView];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(10, 0, 80, 40);
        btn.tag = CellOffset +999+ i;
        [subjBtnAry addObject:@(btn.tag)];
        btn.titleLabel.font = [UIFont systemFontOfSize:14];
        NSDictionary *item = channelAry[i];
        [btn setTitle:item[@"channel_name"] forState:UIControlStateNormal];
        [btn setTitleColor:i == selectedIndex ?[UIColor orangeColor]: KKColor_White_Black forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(chooseChannel:) forControlEvents:UIControlEventTouchUpInside];
        [bgView addSubview:btn];
        if (i != 0) {
            UIButton *delBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            delBtn.frame = CGRectMake(-10, -10, 30, 30);
            [delBtn setImage:[UIImage imageNamed: @"Channel_remove"] forState:UIControlStateNormal];
            [delBtn setImageEdgeInsets:UIEdgeInsetsMake(5, 5, 5, 5)];
            [delBtn addTarget:self action:@selector(dismissBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            delBtn.hidden = YES;
            delBtn.tag = CellOffset * 2 + i;
            [delBtntagAry addObject:@(delBtn.tag)];
            [bgView addSubview:delBtn];
//            UIView *redPoint = [[UIView alloc] initWithFrame:CGRectMake(-3, -3, 10, 10)];
//            redPoint.tag = CellOffset*3+i;
//            NSDictionary *dict = subjBtnAry[i];
//
//            if (dict.allKeys.count ==3) {
//                redPoint.hidden = NO;
//            }else {
//                redPoint.hidden = YES;
//            }
//            redPoint.layer.cornerRadius = 5;
//            redPoint.backgroundColor = [UIColor redColor];
//            [bgView addSubview:redPoint];
        }
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma userAction

/**
 * 拖拽手势
 * 无论怎样拖拽移动 页面上view的tag值是一直按顺序排列的，这个作为排序标准
 */

-(void)pan:(UIPanGestureRecognizer*)recognizer{
//    //
//    UIView *recognizerView = (UIView *)recognizer.view;
//    
//    // 获取移动偏移量
//    CGPoint recognizerPoint = [recognizer translationInView:self.view];
//    NSLog(@"_____%@",NSStringFromCGPoint(recognizerPoint));
//    
//    if (recognizer.state == UIGestureRecognizerStateBegan) {
//        
//        // 开始的时候改变拖动view的外观（放大，改变颜色等）
//        [UIView animateWithDuration:0.2 animations:^{
//            recognizerView.transform = CGAffineTransformMakeScale(1.3, 1.3);
//            recognizerView.alpha = 0.7;
//        }];
//        // 把拖动view放到最上层
//        [self.view bringSubviewToFront:recognizerView];
//        // valuePoint保存最新的移动位置
//        valuePoint = recognizerView.center;
//        
//    }else if(recognizer.state == UIGestureRecognizerStateChanged){
//        // 更新pan.view的center
//        CGFloat x = recognizerView.center.x + recognizerPoint.x;
//        CGFloat y = recognizerView.center.y + recognizerPoint.y;
//        recognizerView.center = CGPointMake(x, y);
//        
//        // 因为拖动会持续执行 所以每次结束都要清空
//        [recognizer setTranslation:CGPointZero inView:channelScroll];
//        
//        for (UIView * bt in channelScroll.subviews) {
//            // 判断是否移动到另一个view区域
//            // CGRectContainsPoint(rect,point) 判断某个点是否被某个frame包含
//            if (CGRectContainsPoint(bt.frame, recognizerView.center)&&bt!=recognizerView)
//            {
//                // 开始位置
//                NSInteger fromIndex = recognizerView.tag - CellOffset;
//                // 需要移动到的位置
//                NSInteger toIndex = bt.tag - CellOffset;
//                NSLog(@"开始位置=%ld  结束位置=%ld",fromIndex,toIndex);
//                // 往后移动
//                if ((toIndex-fromIndex)>0) {
//                    
//                    // 从开始位置移动到结束位置
//                    // 把移动view的下一个view移动到记录的view的位置(valuePoint)，并把下一view的位置记为新的nextPoint，并把view的tag值-1,依次类推
//                    [UIView animateWithDuration:0.2 animations:^{
//                        for (NSInteger i = fromIndex+1; i<=toIndex; i++) {
//                            UIButton * nextBt = (UIButton*)[self.view viewWithTag:CellOffset+i];
//                            nextPoint = nextBt.center;
//                            nextBt.center = valuePoint;
//                            valuePoint = nextPoint;
//                            nextBt.tag--;
//                            
//                        }
//                        recognizerView.tag = CellOffset + toIndex;
////                        [recognizerView setTitle:[NSString stringWithFormat:@"tag值%ld",recognizerView.tag] forState:UIControlStateNormal];
//                    }];
//                }
//                // 往前移动
//                else
//                {
//                    // 从开始位置移动到结束位置
//                    // 把移动view的上一个view移动到记录的view的位置(valuePoint)，并把上一view的位置记为新的nextPoint，并把view的tag值+1,依次类推
//                    [UIView animateWithDuration:0.2 animations:^{
//                        for (NSInteger i = fromIndex-1; i>=toIndex; i--) {
//                            UIView * nextBt = (UIView*)[self.view viewWithTag:CellOffset+i];
//                            nextPoint = nextBt.center;
//                            nextBt.center = valuePoint;
//                            valuePoint = nextPoint;
//                            nextBt.tag++;
//                        }
//                        recognizerView.tag = CellOffset + toIndex;
//                    }];
//                }
//            }
//            
//        }
//    }else if(recognizer.state == UIGestureRecognizerStateEnded){
//        
//        // 结束时候恢复view的外观（放大，改变颜色等）
//        [UIView animateWithDuration:0.2 animations:^{
//            recognizerView.transform = CGAffineTransformMakeScale(1.0, 1.0);
//            recognizerView.alpha = 1;
//            recognizerView.center = valuePoint;
//        }];
//    }
}



- (void)showCloseBtn:(UILongPressGestureRecognizer *)recognizer
{
    deleteBtn.selected = YES;
    [deleteBtn setTitle:@"完成" forState:UIControlStateNormal];
     createBtn.hidden = YES;
    tipLabel.hidden = NO;
    for (NSNumber *num in delBtntagAry) {
        NSInteger btnTag = [num integerValue];
        UIView *view = (UIView *)[self.view viewWithTag:btnTag];
        view.hidden = NO;
    }
    for (NSNumber *count in subjBtnAry) {
        NSInteger btnTag = [count integerValue];
        UIView *view = [self.view viewWithTag:btnTag];
        view.userInteractionEnabled = NO;
    }
    
    //拖动
    UIView *recognizerView = recognizer.view;
    // 禁用其他按钮的拖拽手势
//    for (UIView * bt in channelScroll.subviews) {
//        if (bt != recognizerView) {
//            bt.userInteractionEnabled = NO;
//        }
//
//    }
    
    // 长按视图在父视图中的位置（触摸点的位置）
    CGPoint recognizerPoint = [recognizer locationInView:channelScroll];
    NSLog(@"_____%@",NSStringFromCGPoint(recognizerPoint));
    
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        
        // 开始的时候改变拖动view的外观（放大，改变颜色等）
        [UIView animateWithDuration:0.2 animations:^{
            recognizerView.transform = CGAffineTransformMakeScale(1.3, 1.3);
            recognizerView.alpha = 0.7;
        }];
        
        // 把拖动view放到最上层
        [self.view bringSubviewToFront:recognizerView];
        
        // valuePoint保存最新的移动位置
        valuePoint = recognizerView.center;
        
    }else if(recognizer.state == UIGestureRecognizerStateChanged){
        
        // 更新pan.view的center
        recognizerView.center = recognizerPoint;
        
        /**
         * 可以创建一个继承UIButton的类(MyButton)，这样便于扩展，增加一些属性来绑定数据
         * 如果在self.view上加其他控件拖拽会奔溃，可以在下面方法里面加判断MyButton，也可以把所有按钮放到一个全局变量的UIView上来替换self.view
         
         */
        for (UIView * sub in channelScroll.subviews) {
            // 判断是否移动到另一个view区域
            // CGRectContainsPoint(rect,point) 判断某个点是否被某个frame包含
            if (CGRectContainsPoint(sub.frame, recognizerView.center)&&sub!=recognizerView)
            {
                NSLog(@"bt_______%@",sub);
                // 开始位置
                NSInteger fromIndex = recognizerView.tag - CellOffset;
                
                // 需要移动到的位置
                NSInteger toIndex = sub.tag - CellOffset;
                
                NSLog(@"开始位置=%ld  结束位置=%ld",fromIndex,toIndex);
                
                //数组交换元素
                [exchangeAry exchangeObjectAtIndex:fromIndex withObjectAtIndex:toIndex];
                if (delegate && [delegate respondsToSelector:@selector(sendSubjectAryValue:)]) {
                    [delegate sendSubjectAryValue:exchangeAry];
                }
                // 往后移动
                if ((toIndex-fromIndex)>0) {
                    
                    // 从开始位置移动到结束位置
                    // 把移动view的下一个view移动到记录的view的位置(valuePoint)，并把下一view的位置记为新的nextPoint，并把view的tag值-1,依次类推
                    [UIView animateWithDuration:0.2 animations:^{
                        for (NSInteger i = fromIndex+1; i<=toIndex; i++) {
                            UIView * nextBt = (UIView*)[self.view viewWithTag:CellOffset+i];
                            nextPoint = nextBt.center;
                            nextBt.center = valuePoint;
                            valuePoint = nextPoint;
                            nextBt.tag--;
                        }
                        recognizerView.tag = CellOffset + toIndex;
                    }];
                }
                // 往前移动
                else
                {
                    // 从开始位置移动到结束位置
                    // 把移动view的上一个view移动到记录的view的位置(valuePoint)，并把上一view的位置记为新的nextPoint，并把view的tag值+1,依次类推
                    [UIView animateWithDuration:0.2 animations:^{
                        for (NSInteger i = fromIndex-1; i>=toIndex; i--) {
                            UIView * nextBt = (UIView *)[self.view viewWithTag:CellOffset+i];
                            nextPoint = nextBt.center;
                            nextBt.center = valuePoint;
                            valuePoint = nextPoint;
                            nextBt.tag++;
                        }
                        recognizerView.tag = CellOffset + toIndex;
                        
                    }];
                    
                }
            }
        }
        
    }else if(recognizer.state == UIGestureRecognizerStateEnded){
        // 恢复其他按钮的拖拽手势
//        for (UIView * sub in channelScroll.subviews) {
//            if (sub!=recognizerView) {
//                sub.userInteractionEnabled = YES;
//            }
//        }
        
        // 结束时候恢复view的外观（放大，改变颜色等）
        [UIView animateWithDuration:0.2 animations:^{
            recognizerView.transform = CGAffineTransformMakeScale(1.0, 1.0);
            recognizerView.alpha = 1;
            recognizerView.center = valuePoint;
        }];
    }
    
    
}


-(void)dismissBtnClick:(UIButton *)sender
{
    NSInteger num = sender.tag - CellOffset*2;
    [subjBtnAry removeObjectAtIndex:num];
    if (delegate &&[delegate respondsToSelector:@selector(sendSubjectAryValue:)]) {
        [delegate sendSubjectAryValue:subjBtnAry];
    }
    for (UIView *subView in sender.superview.subviews) {
        [subView removeFromSuperview];
    }
}

- (void)chooseChannel:(UIButton *)sender
{
    selectedIndex = sender.tag - CellOffset-999;
    UIView *redPoint = [self.view viewWithTag:CellOffset*3+selectedIndex];
    redPoint.hidden = YES;
    if (delegate && [delegate respondsToSelector:@selector(selectedChannelChanged:)]) {
        [delegate selectedChannelChanged:selectedIndex];
    }
//    NSDictionary *dict = subjBtnAry[selectedIndex];
//    NSMutableDictionary *newDict = [NSMutableDictionary dictionaryWithDictionary:dict];
//    [newDict removeObjectForKey:@"is_new"];
//    [subjBtnAry replaceObjectAtIndex:selectedIndex withObject:newDict];
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"arrayChange" object:subjBtnAry];
    [self.navigationController popViewControllerAnimated:YES];
    
}


- (IBAction)backBtnClick:(UIButton *)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
}



- (IBAction)createBtnClick:(UIButton *)sender {
    
    FilesViewController *fileVC = [[FilesViewController alloc] init];
    fileVC.nameList = channelAry;
    [self.navigationController pushViewController:fileVC animated:YES];
}


- (IBAction)deleteBtnClick:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected ) {
        [sender setTitle:@"完成" forState:UIControlStateNormal];
        createBtn.hidden = YES;
        tipLabel.hidden = NO;
        for (NSNumber *num in delBtntagAry) {
            NSInteger btnTag = [num integerValue];
            UIView *view = (UIView *)[self.view viewWithTag:btnTag];
            view.hidden = NO;
        }
        for (NSNumber *count in subjBtnAry) {
            NSInteger btnTag = [count integerValue];
            UIView *view = [self.view viewWithTag:btnTag];
            view.userInteractionEnabled = NO;
        }
        
    } else {
        [sender setTitle:@"排序/删除" forState:UIControlStateNormal];
        createBtn.hidden = NO;
        tipLabel.hidden = YES;
        for (NSNumber *num in delBtntagAry) {
            NSInteger btnTag = [num integerValue];
            UIView *view = (UIView *)[self.view viewWithTag:btnTag];
            view.hidden = YES;
        }
        for (NSNumber *count in subjBtnAry) {
            NSInteger btnTag = [count integerValue];
            UIView *view = [self.view viewWithTag:btnTag];
            view.userInteractionEnabled = YES;
        }
    }
}


@end
